package com.ltkj.baseplatform.service.impl;

import com.ltkj.baseplatform.domain.ArtChannel;
import com.ltkj.baseplatform.domain.SerTravelNotes;
import com.ltkj.baseplatform.domain.SerTravelType;
import com.ltkj.baseplatform.domain.bo.ArtContentQueryBo;
import com.ltkj.baseplatform.domain.vo.*;
import com.ltkj.baseplatform.service.*;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.DictUtils;
import com.ltkj.system.api.RemoteShopService;
import com.ltkj.system.api.domain.ShopGoodsDTO;
import com.ltkj.system.api.domain.ShopHotelDTO;
import com.ltkj.system.api.domain.ShopRestaurantDTO;
import com.ltkj.system.api.domain.SysDictData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 查询小程序首页内容service
 *
 * @Author: liupf
 * @Date: 2023/09/03
 * @Description:
 */
@Service
public class HomeContentServiceImpl implements IHomeContentService {

    @Autowired
    private ISerTravelTypeService serTravelTypeService;

    @Autowired
    private IArtContentService artContentService;

    @Autowired
    private ISerTravelNotesService serTravelNotesService;

    @Autowired
    private RemoteShopService remoteShopService;

    @Autowired
    private IArtChannelService artChannelService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询综合推荐分类列表
     *
     * @return 结果
     */
    @Override
    public List<TabDataVo> queryTabData() {
        Object cacheObj = redisService.getCacheObject(CacheConstants.HOME_TAB_TYPE_KEY);
        if (cacheObj != null) {
            return (List<TabDataVo>) cacheObj;
        } else {
            List<SysDictData> homeRecoTablist = DictUtils.getDictCache("home_reco_tablist");
            List<TabDataVo> result = new ArrayList<>();
            for (SysDictData dictData : homeRecoTablist) {
                TabDataVo tabDataVo = new TabDataVo();
                tabDataVo.setId(dictData.getDictCode());
                //"资讯"就使用实际的栏目id
                if ("1".equals(dictData.getDictValue())) {
                    tabDataVo.setId(9L);
                }
                tabDataVo.setTabName(dictData.getDictLabel());
                tabDataVo.setTabType(dictData.getDictValue());
                //游记返回子分类
                if ("2".equals(tabDataVo.getTabType())) {
                    List<TabDataVo> child = new ArrayList<>();
                    //查询子分类
                    List<SerTravelType> serTravelTypes = serTravelTypeService.selectSerTravelTypeList(new SerTravelType());
                    if (!CollectionUtils.isEmpty(serTravelTypes)) {
                        for (SerTravelType serTravelType : serTravelTypes) {
                            TabDataVo tab = new TabDataVo();
                            tab.setId(serTravelType.getTypeId());
                            tab.setTabName(serTravelType.getTypeName());
                            child.add(tab);
                        }
                    }
                    if (!CollectionUtils.isEmpty(child)) {
                        tabDataVo.setChildren(child);
                    }
                }
                result.add(tabDataVo);
            }
            //添加缓存
            redisService.setCacheObject(CacheConstants.HOME_TAB_TYPE_KEY, result, CacheConstants.REFRESH_TIME, TimeUnit.MINUTES);
            return result;
        }
    }

    @Override
    public List<RecoDataVo> queryRecoDataList() {

        Object cacheObj = redisService.getCacheObject(CacheConstants.HOME_TAB_DATA_KEY);
        if (cacheObj != null) {
            return (List<RecoDataVo>) cacheObj;
        }else {
            List<RecoDataVo> resultList = new ArrayList<>();

            //查询游记数据
            getTravelNotesData(resultList);
            //查询资讯数据
            getInfoData(resultList);
            //查询餐饮数据
            getShopRestaurantData(resultList);
            //查询文创数据
            getShopGoodsData(resultList);
            //查询酒店数据
            getShopHotelData(resultList);
            //添加缓存,缓存240分钟
            redisService.setCacheObject(CacheConstants.HOME_TAB_DATA_KEY, resultList, 240L, TimeUnit.MINUTES);
            return resultList;
        }


    }

    /**
     * 查询首页各种元素（弹框公告，通知公告，顶部轮播，游玩路线，游玩攻略，人文风光，热门活动，热门景点，资讯）
     * @return  结果
     */
    @Override
    public AjaxResult getHomeElemData() {
        Object cacheObj = redisService.getCacheObject(CacheConstants.HOME_ELE_DATA_KEY);
        if (cacheObj != null) {
            return (AjaxResult) cacheObj;
        } else {
            AjaxResult ajax = AjaxResult.success();
            //弹框公告
            ajax.put("popNotice", getHomeListDataV2(1L, 1));
            //通知公告
            ajax.put("notice", getHomeListDataV2(2L, 3));
            //顶部轮播
            ajax.put("topCarousel", getHomeListDataV2(3L, 3));
            //游玩路线
            ajax.put("playRoute", getHomeListDataV2(4L, 0));
            //游玩攻略
            ajax.put("playStrategy", getHomeListDataV2(5L, 0));
            //人文风光
            ajax.put("culture", getHomeListDataV2(6L, 0));
            //热门活动
            ajax.put("hotPlay", getHomeListDataV2(7L, 3));
            //热门景点
            ajax.put("hotPlace", getHomeListDataV2(8L, 3));
            //资讯
            ajax.put("info", getHomeListDataV2(9L, 0));
            //添加缓存
            redisService.setCacheObject(CacheConstants.HOME_ELE_DATA_KEY, ajax, CacheConstants.REFRESH_TIME, TimeUnit.MINUTES);
            return ajax;
        }
    }
    /**
     * 查询首页各种元素兼容体育场
     * @return  结果
     */
    @Override
    public AjaxResult getHomeElemDataV2() {
        AjaxResult ajax = AjaxResult.success();
        //弹框公告
        ajax.put("popNotice", getHomeListDataV2(16L, 1));
        //通知公告
        ajax.put("notice", getHomeListDataV2(17L, 3));
        //顶部轮播
        ajax.put("topCarousel", getHomeListDataV2(18L, 3));
        //金刚区
        //ajax.put("kingArea", getHomeListDataV2(19L, 5));
        //商品周边
        ajax.put("goodsAbout", getHomeListDataV2(20L, 5));
        //热门场馆
        ajax.put("hotGym", getHomeListDataV2(21L, 5));
        //活动资讯
        ajax.put("playInfo", getHomeListDataV2(22L, 3));

        return ajax;
    }

    //综合推荐获取资讯数据
    private void getInfoData(List<RecoDataVo> resultList){
        ArtContentQueryBo artContentQueryBo = new ArtContentQueryBo();
        artContentQueryBo.setArticleStatus("1");//必须查询已发布的数据
        artContentQueryBo.setChannelId(9L);//查询资讯数据
        artContentQueryBo.setLimitNum(2);//暂定两条
        artContentQueryBo.setOrderByReco("1");//按照推荐值获取
        List<ArtContentVo> list = artContentService.selectArtContentList(artContentQueryBo);
        for (ArtContentVo artContentVo : list) {
            RecoDataVo recoDataVo = new RecoDataVo();
            recoDataVo.setId(artContentVo.getId());
            recoDataVo.setTitle(artContentVo.getTitle());
            recoDataVo.setDesc(artContentVo.getIntroduction());
            recoDataVo.setTabType("1");
            recoDataVo.setFileType("0");
            //查询缩略图
            recoDataVo.setImgPath(artContentVo.getZoomImgPath());
            resultList.add(recoDataVo);
        }
    }
    //综合推荐获取游记数据
    private void getTravelNotesData(List<RecoDataVo> resultList){
        SerTravelNotes serTravelNotes = new SerTravelNotes();
        Map<String, Object> map = new HashMap<>();
        map.put("limit", 2);
        map.put("orderByReco", 1);//按照推荐值排序查询
        map.put("status", 1);
        serTravelNotes.setParams(map);
        List<SerTravelNotesVo> serTravelNotesVos = serTravelNotesService.selectAppletTravelNotesList(serTravelNotes);
        for (SerTravelNotesVo serTravelNotesVo : serTravelNotesVos) {
            RecoDataVo recoDataVo = new RecoDataVo();
            recoDataVo.setId(serTravelNotesVo.getId());
            recoDataVo.setTitle(serTravelNotesVo.getTitle());
            recoDataVo.setTabType("2");
            recoDataVo.setNickName(serTravelNotesVo.getNickName());
            recoDataVo.setPlaceName(serTravelNotesVo.getAddr());
            recoDataVo.setViewNum(serTravelNotesVo.getViewNum());
            recoDataVo.setAvatar(serTravelNotesVo.getAvatar());
            recoDataVo.setFileType(serTravelNotesVo.getType());
            //设置封面图片路径
            recoDataVo.setImgPath(serTravelNotesVo.getImgPath());
            /*if (!CollectionUtils.isEmpty(serTravelNotesVo.getAttachmentList()) && serTravelNotesVo.getAttachmentList().size() > 0) {
                //取第一张图片展示
                CommAttachment commAttachment = serTravelNotesVo.getAttachmentList().get(0);
                //设置图片路径
                recoDataVo.setImgPath(commAttachment.getAttaPath());
            }*/
            resultList.add(recoDataVo);
        }
    }
    //综合推荐获取文创数据
    private void getShopGoodsData(List<RecoDataVo> resultList){
        ShopGoodsDTO shopGoods = new ShopGoodsDTO();
        Map<String, Object> map = new HashMap<>();
        //这个暂时没用
       /* map.put("orderByColumn", "rec_value");
        map.put("isAsc", "desc");*/
        map.put("limit", 2);
        shopGoods.setParams(map);
        R<List<ShopGoodsDTO>> result = remoteShopService.listGoods(shopGoods);
        if (!StringUtils.isNull(result) && !StringUtils.isNull(result.getData())) {
            List<ShopGoodsDTO> data = result.getData();
            for (ShopGoodsDTO item : data) {
                RecoDataVo recoDataVo = new RecoDataVo();
                recoDataVo.setId(item.getId());
                recoDataVo.setTitle(item.getName());
                recoDataVo.setTabType("3");
                recoDataVo.setFileType("0");
                recoDataVo.setImgPath(item.getImgAbbrev());
                recoDataVo.setViewNum(item.getViewNum());
                resultList.add(recoDataVo);
            }
        }
    }
    //综合推荐获取餐饮数据
    private void getShopRestaurantData(List<RecoDataVo> resultList){
        ShopRestaurantDTO shopRestaurant = new ShopRestaurantDTO();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("limit", 1);
        shopRestaurant.setParams(map1);
        R<List<ShopRestaurantDTO>> resultR1 = remoteShopService.listRestaurant(shopRestaurant);
        if (!StringUtils.isNull(resultR1) && !StringUtils.isNull(resultR1.getData())) {
            List<ShopRestaurantDTO> data = resultR1.getData();
            for (ShopRestaurantDTO item : data) {
                RecoDataVo recoDataVo = new RecoDataVo();
                recoDataVo.setId(item.getId());
                recoDataVo.setTitle(item.getName());
                recoDataVo.setTabType("4");
                recoDataVo.setPlaceName(item.getAddress());
                recoDataVo.setFileType("0");
                recoDataVo.setImgPath(item.getImgAbbrev());
                resultList.add(recoDataVo);
            }
        }
    }
    //综合推荐获取酒店数据
    private void getShopHotelData(List<RecoDataVo> resultList){
        ShopHotelDTO shopHotel = new ShopHotelDTO();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("limit", 1);
        shopHotel.setParams(map2);
        R<List<ShopHotelDTO>> resultR2 = remoteShopService.listHotel(shopHotel);
        if (!StringUtils.isNull(resultR2) && !StringUtils.isNull(resultR2.getData())) {
            List<ShopHotelDTO> data = resultR2.getData();
            for (ShopHotelDTO item : data) {
                RecoDataVo recoDataVo = new RecoDataVo();
                recoDataVo.setId(item.getId());
                recoDataVo.setTitle(item.getName());
                recoDataVo.setTabType("5");
                recoDataVo.setPlaceName(item.getAddress());
                recoDataVo.setFileType("0");
                recoDataVo.setImgPath(item.getImgAbbrev());
                resultList.add(recoDataVo);
            }
        }
    }

    /**
     * 首页单张图片展示数据
     * 弹框公告 ，游玩路线，游玩攻略,人文风光，资讯使用
     * @param channelId
     * @param limitNum
     * @return
     */
    private HomeListVo getHomeData(Long channelId, Integer limitNum){
        ArtChannel channel = artChannelService.selectArtChannelById(channelId);
        HomeListVo homeListVo = new HomeListVo();
        homeListVo.setTypeName(channel.getChannelName());
        homeListVo.setVisitPath(channel.getVisitPath());
        homeListVo.setContentPath(channel.getContentPath());
        homeListVo.setId(channel.getId());
        //资讯默认都是可以点击的
        homeListVo.setCanClick("1");
        homeListVo.setLinkType("0");
        homeListVo.setLinkUrl("");
        //资讯不需要图片
        if(limitNum.intValue() != 0){
            ArtContentQueryBo artContentQueryBo = new ArtContentQueryBo();
            artContentQueryBo.setArticleStatus("1");//必须查询已发布的数据
            artContentQueryBo.setChannelId(channelId);
            artContentQueryBo.setLimitNum(limitNum);
            List<ArtContentVo> list = artContentService.selectArtContentList(artContentQueryBo);
            //这里只有一条，获取图片即可
            for (ArtContentVo artContentVo : list) {
                homeListVo.setImgPath(artContentVo.getImgPath());
                //内容不为空，就是可以点击
                if(org.springframework.util.StringUtils.hasText(artContentVo.getArticleText())){
                    homeListVo.setCanClick("1");
                }else{
                    homeListVo.setCanClick("0");
                }
                homeListVo.setLinkType(artContentVo.getLinkType());
                //linkType=0访问内容详情接口
                homeListVo.setLinkUrl(artContentVo.getLinkUrl());
                //弹框公告最外层就是内容的id
                if(channelId.equals(1L)){
                    homeListVo.setId(artContentVo.getId());
                }
            }
        }
        return homeListVo;
    }
    /**
     * 顶部轮播，热门活动，热门景点,通知公告使用
     * @param channelId
     * @param limitNum
     * @return
     */
    private HomeListVo getHomeListData(Long channelId,Integer limitNum){
        ArtChannel channel = artChannelService.selectArtChannelById(channelId);
        ArtContentQueryBo artContentQueryBo = new ArtContentQueryBo();
        artContentQueryBo.setArticleStatus("1");//必须查询已发布的数据
        artContentQueryBo.setChannelId(channelId);
        artContentQueryBo.setLimitNum(limitNum);
        List<ArtContentVo> list = artContentService.selectArtContentList(artContentQueryBo);
        HomeListVo homeListVo = new HomeListVo();
        homeListVo.setTypeName(channel.getChannelName());
        homeListVo.setVisitPath(channel.getVisitPath());
        homeListVo.setContentPath(channel.getContentPath());
        homeListVo.setId(channel.getId());
        List<CarouselVo> item = new ArrayList<>();
        for (ArtContentVo artContentVo : list) {
            CarouselVo carouselVo = new CarouselVo();
            carouselVo.setTitle(artContentVo.getTitle());
            //文章内容首页没用到
            //carouselVo.setContent(artContentVo.getArticleText());
            carouselVo.setImgPath(artContentVo.getImgPath());
            carouselVo.setContenId(artContentVo.getId());
            //内容不为空，就是可以点击
            if(org.springframework.util.StringUtils.hasText(artContentVo.getArticleText())){
                carouselVo.setCanClick("1");
            }else{
                carouselVo.setCanClick("0");
            }
            carouselVo.setLinkType(artContentVo.getLinkType());
            carouselVo.setLinkUrl(artContentVo.getLinkUrl());
            item.add(carouselVo);
        }
        homeListVo.setItem(item);
        return homeListVo;
    }


    /**
     * 体育场首页使用，处理返回给首页的内容数据（后续生态岛首页也使用）
     * @param channelId
     * @param limitNum
     * @return
     */
    private HomeDataVo getHomeListDataV2(Long channelId,Integer limitNum){
        ArtChannel channel = artChannelService.selectArtChannelById(channelId);
        HomeDataVo homeDataVo = new HomeDataVo();
        homeDataVo.setTypeName(channel.getChannelName());
        homeDataVo.setVisitPath(channel.getVisitPath());
        homeDataVo.setContentPath(channel.getContentPath());
        homeDataVo.setId(channel.getId());
        if(limitNum.intValue() != 0){
            ArtContentQueryBo artContentQueryBo = new ArtContentQueryBo();
            artContentQueryBo.setArticleStatus("1");//必须查询已发布的数据
            artContentQueryBo.setChannelId(channelId);
            artContentQueryBo.setLimitNum(limitNum);
            List<ArtContentVo> list = artContentService.selectArtContentList(artContentQueryBo);
            List<DataItem> item = new ArrayList<>();
            for (ArtContentVo artContentVo : list) {
                DataItem dataItem = new DataItem();
                //标题
                dataItem.setTitle(artContentVo.getTitle());
                //图片路径
                dataItem.setImgPath(artContentVo.getImgPath());
                //文章id
                dataItem.setContenId(artContentVo.getId());
                //内容不为空，就是可以点击
                if(org.springframework.util.StringUtils.hasText(artContentVo.getArticleText())){
                    dataItem.setCanClick("1");
                }else{
                    dataItem.setCanClick("0");
                }
                //链接类型
                dataItem.setLinkType(artContentVo.getLinkType());
                //链接地址
                dataItem.setLinkUrl(artContentVo.getLinkUrl());
                dataItem.setLatitude(artContentVo.getLatitude());
                dataItem.setLongitude(artContentVo.getLongitude());
                dataItem.setAppId(artContentVo.getAppId());
                item.add(dataItem);
            }
            homeDataVo.setItem(item);
        }
        return homeDataVo;
    }
}
